package com.miszczu.dziennik;

import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.miszczu.bo.MessagesBo;
import com.miszczu.bo.UsersBo;
import com.miszczu.dao.UsersDao;
import com.miszczu.forms.MessageForm;
import com.miszczu.model.Messagesreceived;
import com.miszczu.model.Users;

@Controller
public class MessagesController {

	@Autowired
	MessagesBo messagesBo;
	
	@Autowired
	UsersBo usersBo;
	
	@RequestMapping(value = "/teacher/message/new", method = RequestMethod.GET)
	public String composeMessage(Model model) {
		
		MessageForm messageForm = new MessageForm();
		
		model.addAttribute("messageForm", messageForm);
		
		return "teacher_new_message";
	}
	
	@RequestMapping(value = "/teacher/messages", method = RequestMethod.GET)
	public String showMessagesList(Model model, @RequestParam(value="page", required = false) Integer page) {
		
		PagedListHolder<Messagesreceived> messagesHolder = getMessagesPageHolder(page);
		
		model.addAttribute("messages", messagesHolder.getPageList());
		model.addAttribute("messagesHolder", messagesHolder);
		
		return "teacher_messages_list";
	}
	
	@RequestMapping(value = "/teacher/message/show", method = RequestMethod.GET)
	public String showMessage(Model model, @RequestParam(value="id", required = true) Integer id) {
		
		Messagesreceived message = messagesBo.getOneReceivedMessage(id);
		
		if(message == null) {
			return "not_found";
		}
		
		model.addAttribute("message", message);
		
		return "teacher_message_show";
	}
	
	@RequestMapping(value = "/teacher/message/delete", method = RequestMethod.GET)
	public String deleteReceivedMessage(Model model, @RequestParam(value="id", required = true) Integer id) {
		
		Messagesreceived message = messagesBo.getOneReceivedMessage(id);
		
		if(message == null) {
			return "not_null";
		}
		
		messagesBo.deleteReceivedMessage(id);
		
		return "redirect:/teacher/messages";
	}
	
	private PagedListHolder<Messagesreceived> getMessagesPageHolder(Integer page) {
		
		Users loggedUser = usersBo.getLoggedUser(); 
		List<Messagesreceived> messages = messagesBo.getReceivedMessages(loggedUser);
		PagedListHolder<Messagesreceived> pagedListHolder = new PagedListHolder<Messagesreceived>(messages);
		pagedListHolder.setPageSize(20);
		
		if(page == null) {
			page = 0;
		}
		pagedListHolder.setPage(page);
		
		return pagedListHolder;
	}
}
